<template>
  <div class="index-container">
    <x-header title="SAC">
      <select  @change="changeLanguage" v-model="language" slot="overwrite-left" class="header-selected">
        <option value="zh-CN">{{$t('vux.zhCN')}}</option>
        <option value="en">{{$t('vux.en')}}</option>
      </select>
      <select @change="changeCoinType" v-model="lineType" class="header-selected" slot="right">
        <option value="CNY">CNY</option>
        <option value="BTC">BTC</option>
        <option value="USDT">USDT</option>
      </select>
    </x-header>
    <section class="line-container">
      <!--<p style="color: #fff;text-align: left;padding: 0 .15rem">￥10.2354 <span style="background-color: #0BB20C;border-radius: 4px;line-height: 1.4">+7.33%</span></p>-->
      <div style="text-align: left;color: #fff;padding: 0 .4rem">
        <p style="font-size: .3rem;line-height: 1.2">{{totalPrice}}</p>
        <p style="line-height: 1.2">{{$t('volume')}}(24h)：{{tradeTotal}}</p>
        <p style="line-height: 1.2">{{$t('market value')}}：{{marketPrice}}</p>
      </div>
      <div id="myChart" style="height: 28vh"></div>
      <!--<div>-->
        <!--<v-chart :data="data">-->
          <!--<v-line series-field="type" />-->
        <!--</v-chart>-->
      <!--</div>-->
      <!--<div class="selected-btn">-->
        <!--<div class="inner">-->
          <!--<span :class="{'active': searchType === 'today'}" @click="doSearch('today')">{{$t('today')}}</span>-->
          <!--<span :class="{'active': searchType === 'week'}" @click="doSearch('week')">{{$t('lastweek')}}</span>-->
          <!--<span :class="{'active': searchType === 'month'}" @click="doSearch('month')">{{$t('lastmonth')}}</span>-->
          <!--<span :class="{'active': searchType === 'three_month'}" @click="doSearch('three_month')">{{$t('lastquarter')}}</span>-->
          <!--<span :class="{'active': searchType === 'year'}" @click="doSearch('year')">{{$t('lastyear')}}</span>-->
          <!--<span :class="{'active': searchType === 'all'}" @click="doSearch('all')">{{$t('total')}}</span>-->
        <!--</div>-->
      <!--</div>-->
    </section>
    <div class="count">
      <grid :show-lr-borders=false>
        <grid-item :link="{path:'/CNY'}">
          <p slot="label" class="money">{{cny}}</p>
          <p class="title">CNY</p>
        </grid-item>
        <grid-item :link="{path:'/SAC'}">
          <p slot="label" class="money">{{sac}}</p>
          <p class="title">SAC</p>
        </grid-item>
      </grid>
    </div>
    <section class="menu">
      <grid :show-lr-borders="false" :show-vertical-dividers="false">
        <!--:link="{path:'/register'}"-->
        <grid-item  @click.native="goMenu('register')">
          <img slot="icon" src="../assets/img/menu2.png">
          <span slot="label">
            {{$t('register')}}
          </span>
        </grid-item>
        <!--:link="{path:'/myteam'}"-->
        <grid-item  @click.native="goMenu('myteam')">
          <img slot="icon" src="../assets/img/menu6.png">
          <span slot="label">
            {{$t('my team')}}
          </span>
        </grid-item>
      </grid>
      <grid :show-lr-borders="false" :show-vertical-dividers="false">
        <!--:link="{path:'/mill2'}"-->
        <grid-item  @click.native="goMenu('mill2')">
          <img slot="icon" src="../assets/img/millmarket.png">
          <span slot="label">
            {{$t('index.millmarket')}}
          </span>
        </grid-item>
        <!--:link="{path:'/master'}"-->
        <grid-item @click.native="goMenu('master')">
          <img slot="icon" src="../assets/img/menu5.png">
          <span slot="label">
            {{$t('myminer')}}
          </span>
        </grid-item>
        <!--<grid-item  :link="{path:'/tradelist'}">-->
          <!--<img slot="icon" src="../assets/img/menu1.png">-->
          <!--<span slot="label">-->
            <!--{{$t('mybuy')}}-->
          <!--</span>-->
        <!--</grid-item>-->
      </grid>
      <grid :show-lr-borders="false" :show-vertical-dividers="false">
        <!--:link="{path:'/MyEntryOrders'}"-->
        <grid-item @click.native="goMenu('MyEntryOrders')">
          <img slot="icon" src="../assets/img/menu4.png">
          <span slot="label">
            {{$t('index.sell')}}
          </span>
        </grid-item>
        <!--:link="{path:'/cashLog'}"-->
        <grid-item  @click.native="goMenu('cashLog')">
          <img slot="icon" src="../assets/img/menu3.png">
          <span slot="label">
            {{$t('cashLog')}}
          </span>
        </grid-item>
      </grid>
    </section>
  </div>
</template>

<i18n>
  mybuy:
    en: myPurchase
    zh-CN: 交易记录
  register:
    en: Register
    zh-CN: 注册
  cashLog:
    en: CashLog
    zh-CN: 财务明细
  mysale:
    en: Sales
    zh-CN: 挂单
  myminer:
    en: myMiner
    zh-CN: 我的矿机
  transfer:
    en: Transfer
    zh-CN: 转账
  today:
    en: Today
    zh-CN: 1天
  lastweek:
    en: Week
    zh-CN: 1周
  lastmonth:
    en: Month
    zh-CN: 1月
  lastquarter:
    en: ThreeMonth
    zh-CN: 3月
  lastyear:
    en: LastYear
    zh-CN: 1年
  waring:
    en: Warning
    zh-CN: 警告
  no authered:
    en: Please Complete Info!
    zh-CN: 请完善信息
  market value:
    en: Market Value
    zh-CN: 市值
  volume:
    en: Global Transaction volume
    zh-CN: 全球交易量
  index.millmarket:
    en: Mill Market
    zh-CN: 矿机商城
  index.sell:
    en: Trade Market
    zh-CN: 交易市场
</i18n>

<script>
  import {dateFormat, Grid, GridItem, VChart, VLine, VAxis, VTooltip, XHeader} from 'vux'
  import {mapActions} from 'vuex'
  // 引入基本模板
  let echarts = require('echarts/lib/echarts')
  let setInt
  // 引入柱状图组件
  require('echarts/lib/chart/line')
  require('echarts/lib/component/legend')
  require('echarts/lib/component/tooltip')
  export default {
    name: 'home',
    components: {
      dateFormat,
      Grid,
      GridItem,
      VChart,
      VLine,
      VAxis,
      VTooltip,
      XHeader
    },
    data () {
      return {
        data: [],
        cny: 0,
        sac: 0,
        lineData: '',
        time: 'all',
        rate: 6,
        marketPrice: 0,
        tradeTotal: 0,
        price: 0,
        language: localStorage.language,
        lineType: 'CNY',
        totalPrice: '',
        searchType: 'all'
      }
    },
    created () {
      // 初始化
      this.init()
      this.auther()
      this.getLineStatic()
      if (!localStorage.Haslogin) {
        this.$vux.alert.show({
          title: '公告',
          content: '尊敬的用户:由于平台要进行改版，今天会进行改版前的测试工作，需要重新下载app，此次测试时间为2小时，9月1日20:00开始测试，测试期间会员请勿登录账号、望用户知晓!',
          onShow () {
            console.log('Plugin: I\'m showing')
          },
          onHide () {
            localStorage.Haslogin = true
          }
        })
      }
      if (!localStorage.Haslogin) {
        this.$vux.alert.show({
          title: '公告',
          content: '尊敬的用户您好！为了更好地将完善的产品和服务提供给合作伙伴及其客户，经过研发部门精心制作与调试，我们即将对平台全新改版升级。改版升级后的平台在整体风格、内容展现、栏目设置以及功能使用等多个方面都进行了升级和优化。新版平台相比于现在的平台界面更大气、更简洁美观，项目分类更加清晰，更贴合大家的使用习惯和体验。升级期间所有功能均可正常操作，感谢大家支持、敬请期待！',
          onShow () {
            console.log('Plugin: I\'m showing')
          },
          onHide () {
            localStorage.Haslogin = true
          }
        })
      }
    },
    // mounted () {
    //   this.getLineStatic()
    //   setInt = setInterval(this.getLineStatic, 10000)
    // },
    methods: {
      ...mapActions(['updateValitdate']),
      auther () {
        let vue = this
        vue.get({
          url: `api/account/get_index_info?token=${localStorage.token}`,
          success: function (data) {
            // console.log(data.data)
            let info = data.data
            if (data.code === 1) {
              if (!info.alipay) {
                vue.$store.dispatch('updateValitdate', {status: true})
                // vue.$vux.confirm.show({
                //   title: vue.$t('waring'),
                //   content: vue.$t('no authered'),
                //   onCancel () {
                //   },
                //   onConfirm () {
                //     vue.$router.push({path: '/personalinfo'})
                //   }
                // })
                // vue.$vux.alert.show({
                //   title: vue.$t('waring'),
                //   content: vue.$t('no authered'),
                //   onHide () {
                //     vue.$router.push({path: '/personalinfo'})
                //   }
                // })
                return false
              }
              if (!info.bank_card) {
                vue.$store.dispatch('updateValitdate', {status: true})
                // vue.$vux.confirm.show({
                //   title: vue.$t('waring'),
                //   content: vue.$t('no authered'),
                //   onCancel () {
                //   },
                //   onConfirm () {
                //     vue.$router.push({path: '/personalinfo'})
                //   }
                // })
                return false
              }
              // if (!info.is_certification) {
              //   vue.$vux.alert.show({
              //     title: vue.$t('waring'),
              //     content: vue.$t('no authered'),
              //     onHide () {
              //       vue.$router.push({path: '/personalinfo'})
              //     }
              //   })
              //   return false
              // }
              if (!info.wechat) {
                vue.$store.dispatch('updateValitdate', {status: true})
                // vue.$vux.confirm.show({
                //   title: vue.$t('waring'),
                //   content: vue.$t('no authered'),
                //   onCancel () {
                //   },
                //   onConfirm () {
                //     vue.$router.push({path: '/personalinfo'})
                //   }
                // })
                return false
              }
              if (!info.pay_password) {
                vue.$store.dispatch('updateValitdate', {status: true})
                // vue.$vux.confirm.show({
                //   title: vue.$t('waring'),
                //   content: vue.$t('no authered'),
                //   onCancel () {
                //   },
                //   onConfirm () {
                //     vue.$router.push({path: '/personalinfo'})
                //   }
                // })
                return false
              }
            } else if (data.code === 0) {
              vue.$vux.toast.show({
                text: `${data.msg}`,
                type: 'text'
              })
            }
          },
          error: function (data) {
            console.log(data)
          }
        })
      },
      init () {
        // this.getLineStatic()
      },
      changeCoinType () {
        this.getLineStatic(true)
      },
      getLineStatic (loading) {
        let vue = this
        let url = 'api/index/index'
        let showLoading
        loading ? showLoading = loading : showLoading = false
        vue.get({
          url: url,
          showloading: showLoading,
          params: {
            token: localStorage.token,
            time: vue.time
          },
          success: function (data) {
            if (data.code === 1) {
              vue.cny = data.data.cny
              vue.sac = data.data.sac
              vue.rate = data.data.rate
              localStorage.language === 'zh-CN' ? vue.tradeTotal = (data.data.volume / 10000).toFixed(0) + ' 万' : vue.tradeTotal = (data.data.volume / 1000000).toFixed(2) + ' million'
              localStorage.language === 'zh-CN' ? vue.price = '￥ ' + (data.data.price * data.data.rate).toFixed(2) : vue.price = '$ ' + (data.data.price).toFixed(2)
              localStorage.language === 'zh-CN' ? vue.marketPrice = '￥ ' + (data.data.market / 100000000).toFixed(2) + '亿' : vue.marketPrice = '$' + (data.data.market / data.data.rate / 1000000000).toFixed(2) + ' billion '
              vue.lineData = data.data.Kline
              vue.drawLine()
            }
          }
        })
      },
      drawLine () {
        let vm = this
        let data = vm.lineData
        // console.log(data)
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(document.getElementById('myChart'))
        // let xAxis = data.market_cap_usd.map(function (item) {
        //   return dateFormat(item[0], 'YYYY-MM-DD')
        // })
        let xAxis
        let dataLine
        let label
        if (vm.lineType === 'CNY') {
          xAxis = data.price_usd.map(function (item) {
            return dateFormat(item[0], 'YYYY-MM-DD')
          })
          vm.totalPrice = 'CNY: ' + (data.price_usd[data.price_usd.length - 1][1] * vm.rate).toFixed(2)
          dataLine = data.price_usd.map(function (item) {
            return item[1] * vm.rate
          })
          label = '价格(CNY)'
        }
        if (vm.lineType === 'BTC') {
          vm.totalPrice = 'BTC: ' + data.price_btc[data.price_usd.length - 1][1]
          xAxis = data.price_btc.map(function (item) {
            return dateFormat(item[0], 'YYYY-MM-DD')
          })
          dataLine = data.price_btc.map(function (item) {
            return item[1] * vm.rate
          })
          label = '价格(BTC)'
        }
        if (vm.lineType === 'USDT') {
          vm.totalPrice = 'USDT: ' + data.price_usd[data.price_usd.length - 1][1].toFixed(2)
          xAxis = data.price_usd.map(function (item) {
            return dateFormat(item[0], 'YYYY-MM-DD')
          })
          dataLine = data.price_usd.map(function (item) {
            return item[1]
          })
          label = '价格(USDT)'
        }
        // market_cap_use 市场价
        // price_btc 价格btc
        // price_usd 价格美元
        // volume_usd 24小时？
        // let dataLine = data.market_cap_usd.map(function (item) {
        //   return item[1]
        // })
        // let dataLine2 = data.price_btc.map(function (item) {
        //   return item[1]
        // })

        // 绘制图表
        myChart.setOption({
          color: ['#7CB5EC', '#009933', '#F7931A'],
          tooltip: {
            trigger: 'axis'
          },
          // legend: {
          //   selectedMode: false,
          //   data: ['市值', '价格(BTC)', '价格(美元)']
          // },
          grid: {
            right: 0,
            left: 45,
            top: 20,
            bottom: 40
          },
          xAxis: {
            data: xAxis,
            boundaryGap: false,
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#fff'
            }
          },
          yAxis: [
            // {
            //   color: '#fff',
            //   splitLine: {
            //     lineStyle: {
            //       // type: 'dotted',
            //       color: '#dfdfdf'
            //     }
            //   },
            //   axisLine: {
            //     show: false
            //   },
            //   axisTick: {
            //     show: false
            //   },
            //   axisLabel: {
            //     color: '#fff',
            //     formatter: (value, index) => {
            //       return '$' + (value / 100000000) + '亿'
            //     }
            //   }
            // },
            // {
            //   name: '价格(BTC)',
            //   show: false,
            //   splitLine: {
            //     lineStyle: {
            //       // type: 'dotted',
            //       color: '#dfdfdf'
            //     }
            //   },
            //   axisLine: {
            //     show: false
            //   },
            //   axisTick: {
            //     show: false
            //   },
            //   axisLabel: {
            //     color: '#fff'
            //   }
            // },
            {
              // name: '价格(美元)',
              splitLine: {
                lineStyle: {
                  type: 'dotted',
                  color: '#dfdfdf'
                }
              },
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              },
              axisLabel: {
                color: '#fff'
              }
            }
          ],
          series: [
            // {
            //   name: '市值',
            //   type: 'line',
            //   data: dataLine,
            //   smooth: false,
            //   symbol: 'none'
            // },
            // {
            //   name: '价格(BTC)',
            //   type: 'line',
            //   yAxisIndex: 1,
            //   data: dataLine2,
            //   smooth: false,
            //   symbol: 'none'
            // },
            {
              name: label,
              type: 'line',
              // yAxisIndex: 2,
              data: dataLine,
              smooth: false,
              symbol: 'none',
              itemStyle: {
                normal: {
                  color: '#fff'
                }
              },
              areaStyle: {
                normal: {
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: '#416aa7'
                  }, {
                    offset: 1,
                    color: '#416aa7'
                  }])
                }
              }
            }
          ]
        })
      },
      doSearch (type) {
        this.searchType = type
        this.time = type
        this.getLineStatic(true)
      },
      changeLanguage () {
        this.getLineStatic(true)
        this.$i18n.set(this.language)
        localStorage.language = this.language
      },
      goMenu (path) {
        let vue = this
        if (vue.$store.state.needValidate) {
          vue.$vux.confirm.show({
            title: vue.$t('waring'),
            content: vue.$t('no authered'),
            onCancel () {
            },
            onConfirm () {
              vue.$router.push({path: '/personalinfo'})
            }
          })
        } else {
          this.$router.push({path: '/' + path})
        }
      }
    },
    beforeRouteLeave (to, from, next) {
      window.clearInterval(setInt)
      next()
    }
  }
</script>

<style lang="less" scoped>
  @import "../assets/style/style.less";
  .index-container {
    background-color: #EAEAEA;
    min-height: 100%;
  }
  .line-container{
    /*height: 38vh;*/
    background-color: @theme-color;
    text-align: center;
    .selected-btn span{
      background-color: #fff;
      color: #333;
      padding: 0 .1rem;
      float: left;
      border: 1px solid #dfdfdf;
      border-right: 0;
      font-size: .14rem;
      line-height: 1.8;
      &:last-child {
        border-right: 1px solid #dfdfdf;
      }
    }
    .active {
      background-color: #0d95e8!important;
      border-color: #0d95e8!important;
      color: #fff!important;
    }
    .inner {
      display: inline-block;
      &:after{
        clear: both;
        content: '';
        display: block;
        visibility: hidden;
      }
    }
  }
  .menu {
    /*background-color: #fafafa;*/
    text-align: center;
    padding: 0 15px;

    .weui-grid{
      background-color: white !important;
      border-radius: 8px;
      margin-right: .1rem;
      margin-bottom: .1rem;
      width: 49% !important;
      /*box-shadow: 0px 0px 5px rgba(0,0,0, .6);*/
    }
    .weui-grids>:last-child{
      margin-right: 0rem;
    }
  }
  .weui-grids:before {
    content: none!important;
  }
  .weui-grid:after {
    content: none!important;
  }
  .count {
    /*background-color: #fff;*/
    background: url("../assets/img/bg.png") no-repeat;
    background-size:cover ;
    text-align: center;
    margin: 15px 15px;
    border-radius: 10px;
    border: 1px solid #dfdfdf;
    .weui-grids:before {
      content: none!important;
    }

    /*.weui-grids{*/
     /**/
    /*}*/
    .weui-grids:after {
      content: none!important;
    }
    .weui-grid:after {
      content: none!important;
    }
    .weui-grid:last-child:before {
      content: none!important;
    }
    .money{
      font-size: 0.4rem;
      font-weight: bold;
    }
    .title{
      font-size: 0.28rem;
      color:white;
    }
    .money{
      color: white !important;
    }
    a{
      padding: 17px 0px;
      color: white !important;
    }
  }
</style>
